package com.atguigu.spzx.pay.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.pay.service.PayService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/order/alipay/")
public class PayController {

    @Autowired
    PayService payService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @GetMapping("/submitAlipay/{orderNo}")
    public Result<String> submitAlipay(@PathVariable String orderNo){
        //调用阿里支付,得到一个跳转到支付宝的一个表单.
        String alipayForm = payService.submitAlipay(orderNo);
        return Result.ok(alipayForm);
    }


    /*
    * 支付宝回调接口,系统根据支付宝的回调结果更新系统信息.*/
    @PostMapping("/callback/notify")
    @SneakyThrows
    public String notify(@RequestParam Map<String, String> paramMap , HttpServletRequest request){
        String publicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlPTt6SnstNj/dp5G2s0Yaw91vIL9USueUh+2nczz0EQP9ku1cGsfh+4PZKFBbKYkBLR5cVJzsOt0LCBWbSxVQ6AN5tCv3GdMN0ph6Lmpnb/WvumfyQ9E4XyYqscb0KgR5UTq8+PYIUBc1CE1LLaXqx0YllzO+ho+PDDlDltZRqTTryyNy/grxzPOLDHIDsXzS3rqBkOZeSu39kRJAmi6tpSwr6PpW1ztmB+KOntJBKIAKFXNhpIWwXRO2ofOZmU+mZrpRluc+H4N8Z3hEroQwzfunJ/CFNapRXRs4Swxs2A0qvDHH3NN8N3UngRPHr9o5droWaRST+VofFmUjuC1mwIDAQAB";
        //对请求进行验签,判断是否是支付宝的请求.
        boolean signVerified = AlipaySignature.rsaCheckV1(paramMap, publicKey, "utf-8", "RSA2");
        if (signVerified){
            System.out.println("验签成功.");
        }
        System.out.println("系统根据支付宝的回调结果更新系统信息");

        //获取到订单号
        String orderNo = paramMap.get("out_trade_no");

        try {
            payService.handlePaymentCallback(paramMap);
            //TODO 成功修改订单状态 异步处理


            rabbitTemplate.convertAndSend("order.status.exchange","order.success",orderNo);

            return "success";
        } catch (Exception e) {
            //交易失败
            System.out.println("交易失败，打印失败日志"+e.getMessage());
            //TODO  交易失败，退款业务。异步
            System.out.println("正在处理退款----------------");
            //TODO 失败修改订单状态 异步处理
            rabbitTemplate.convertAndSend("order.status.exchange","order.failed",orderNo);
            e.printStackTrace();
            return "failure";
        }

    }


}
